package com.hkfn.rfb.common.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.hkfn.rfb.MainActivity;
import com.hkfn.rfb.R;
import com.hkfn.rfb.common.MyHandler;
import com.hkfn.rfb.common.bean.BannerModel;
import com.hkfn.rfb.common.bean.BaseModel;
import com.hkfn.rfb.common.bean.ConstData;
import com.hkfn.rfb.common.fragment.BaseFragment;
import com.hkfn.rfb.common.utils.ActivityCollecter;
import com.hkfn.rfb.common.utils.DialogUtils;
import com.hkfn.rfb.common.utils.ScreenUtils;
import com.hkfn.rfb.common.utils.StringUtils;
import com.hkfn.rfb.common.utils.SystemBarTintManager;
import com.hkfn.rfb.common.utils.ToastUtils;
import com.hkfn.rfb.common.utils.Utils;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BaseActivity extends AppCompatActivity {

    private BaseFragment mCurrentBaseFragment;

    // 上次点击动作时间
    private long lastClickTime = 0;
    // 是否正在刷新
    public boolean isRefreshing = false;
    /**
     * 记录触摸结束时间
     */
    public long touchOverTime = 0;



    protected MyHandler handler;

    private Dialog sqCodeContentDialog;

    public boolean isExitLogin = false;

    private Dialog permissionDialog;

    private final static int REQUEST_SETTING_WHAT = 111;
    private final static int REQUEST_REQUEST_CODE = 112;
    private final static int REQUEST_REQUEST_SQ_CODE = 113;
    private static final int REQUEST_CODE_SCAN = 114;// 跳转到扫一扫页面

    /**
     * 需要向用户申请的权限列表
     */
    private static String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new MyHandler(this) {

            @Override
            public void dealWithMsg(Message msg) {
                // TODO Auto-generated method stub
                dealWithMyMsgs(msg);
            }
        };
        ActivityCollecter.addActivity(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollecter.removeActivity(this);
        DialogUtils.closeDialog(sqCodeContentDialog);
        DialogUtils.closeDialog(permissionDialog);
    }


    protected void dealWithMyMsgs(Message msg) {
    }

    /**
     * 点击动作汇总
     * @param baseModel
     */
    public void setClickAction(BaseModel baseModel){
        setClickAction(baseModel, null);
    }

    public void setClickAction(String actionType, String actionValue, String actionTitle, HashMap<String, String> hashMap){
        setClickAction(actionType, actionValue, actionTitle, hashMap, null);
    }

    public void setClickAction(String actionType, String actionValue, String actionTitle, HashMap<String, String> hashMap, Bundle bundle){
        BannerModel bannerModel = new BannerModel();
        bannerModel.setActionTitle(actionTitle);
        bannerModel.setActionType(actionType);
        bannerModel.setActionValue(actionValue);
        if (null == bundle){
            bundle = new Bundle();
        }
        HashMap<String, String> url_params = null;
        if (bundle.containsKey(ConstData.ACTIONPARAMS)){
            url_params = (HashMap<String, String>) bundle.getSerializable(ConstData.ACTIONPARAMS);
        }
        if (null == hashMap){
            hashMap = new HashMap<>();
        }
        if (null != url_params) {
            hashMap.putAll(url_params);
        }
        bannerModel.setActionParams(hashMap);
        setClickAction(bannerModel, bundle);
    }

    /**
     * 点击动作汇总
     * @param baseModel
     */
    public void setClickAction(BaseModel baseModel, Bundle skipBundle){
        setClickAction(baseModel, skipBundle, 0);
    }

    /**
     * 点击动作汇总
     * @param baseModel
     */
    public void setClickAction(BaseModel baseModel, Bundle skipBundle, int resquestCode){
        if (null == baseModel){
            return;
        }
        String actionType = baseModel.getActionType();
        String actionValue = baseModel.getActionValue();
        if (StringUtils.isEmpty(actionType)){
            return;
        }
        if (null == skipBundle){
            skipBundle = new Bundle();
        }
        skipBundle.putString(ConstData.ACTIONTITLE, baseModel.getActionTitle());
        skipBundle.putString(ConstData.ACTIONVALUE, baseModel.getActionValue());
        skipBundle.putSerializable(ConstData.ACTIONPARAMS, baseModel.getActionParams());
        skipBundle.putSerializable(ConstData.ACTIONMODLE, baseModel);
        switch (actionType){
            case ConstData.SHOWFRAG:
                openActivity(ShowFragActivity.class, skipBundle, resquestCode);
                break;
            // 通过页面路径跳转
            case ConstData.PAGE_PATH:
                skipToTargetActivityByName(actionValue, baseModel.getActionParams(), skipBundle);
                break;
            // 跳转到扫一扫页面
            case ConstData.SQCODE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions(true);
                }else {
                    skipToSqCode(null);
                }
                break;
            //  拨打电话
            case ConstData.PHONE:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+actionValue));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    /**
     * 通过activity的名打开activity
     *
     * @param activityName
     * @param params
     */
    private void skipToTargetActivityByName(String activityName, HashMap<String, String> params, Bundle bundle) {
        try {
            if (null == bundle){
                bundle = new Bundle();
            }
            if (null == params){
                params = new HashMap<>();
            }
            Class targetClass = Class.forName(activityName);
            for (String key : params.keySet()) {
                bundle.putString(key, params.get(key));
            }
            openActivity(targetClass, bundle, 0);
        } catch (Exception e) {
        }
    }

    /**
     * 打开一个activity
     * @param mClass
     */
    public void openActivity(Class<?> mClass){
        openActivity(mClass, new Bundle(), 0);
    }

    /**
     * 打开一个activity
     * @param mClass
     * @param bundle
     * @param resquestCode
     */
    public void openActivity(Class<?> mClass, Bundle bundle, int resquestCode){
        Intent intent = new Intent(this, mClass);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        if (0 == resquestCode) {
            startActivity(intent);
        }else {
            startActivityForResult(intent, resquestCode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_CODE_SCAN:
                if (resultCode == -1) {
                    if (data != null) {
                        final String content = data.getStringExtra(Constant.CODED_CONTENT);
                        if (!StringUtils.isEmpty(content)){
                            // 扫描二维码成功方法
                            if (content.startsWith("http")){
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setActionType(ConstData.WEB);
                                bannerModel.setActionValue(content);
                                setClickAction(bannerModel);
                            }else {
                                DialogUtils.closeDialog(sqCodeContentDialog);
                                sqCodeContentDialog = DialogUtils.createSureAndCancelDialog(this,
                                        "扫描结果", content, "取消", "复制", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                DialogUtils.closeDialog(sqCodeContentDialog);
                                            }
                                        }, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Utils.copyToClipBoard(BaseActivity.this, content, "复制成功");
                                                DialogUtils.closeDialog(sqCodeContentDialog);
                                            }
                                        });
                                DialogUtils.showDialog(sqCodeContentDialog);
                            }
                        }
                    }
                }
                break;
            case REQUEST_SETTING_WHAT:
                if (isAllRequestedPermissionGranted()) {
                    permissionNextTips(false);
                } else {
                    Toast.makeText(this, "部分权限被拒绝获取", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    /**
     * 跳转到扫一扫页面
     * @param bundle
     */
    public void skipToSqCode(Bundle bundle){
        if (null == bundle){
            bundle = new Bundle();
        }
        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        config.setDecodeBarCode(true);//是否扫描条形码 默认为true
        config.setReactColor(R.color.main_color);//设置扫描框四个角的颜色 默认为白色
        config.setFrameLineColor(R.color.main_color);//设置扫描框边框颜色 默认无色
        config.setScanLineColor(R.color.main_color);//设置扫描线的颜色 默认白色
        config.setFullScreenScan(true);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描

        bundle.putSerializable(Constant.INTENT_ZXING_CONFIG, config);
        openActivity(CaptureActivity.class, bundle, REQUEST_CODE_SCAN);
    }


    /**
     * 设置界面全屏
     */
    public void setFullScreen(){
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
    }

    /**
     * 添加fragment到activity
     * @param viewId fragment填充的位置
     * @param baseFragment 填充的对象
     */
    protected void addFragment(int viewId, BaseFragment baseFragment) {
        try {
            if(null == baseFragment || baseFragment.equals(mCurrentBaseFragment)) {
                return;
            }

            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            // 隐藏已显示的Fragment
            if (null != mCurrentBaseFragment) {
                fragmentTransaction.hide(mCurrentBaseFragment);
            }

            if (baseFragment.isAdded()) {
                fragmentTransaction.show(baseFragment);
            }
            else {
                fragmentTransaction.add(viewId, baseFragment, baseFragment.getClass().getSimpleName());
            }
            fragmentTransaction.commitAllowingStateLoss();
            mCurrentBaseFragment = baseFragment;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 替换fragment到activity
     * @param viewId fragment填充的位置
     * @param baseFragment 填充的对象
     */
    protected void replaceFragment(int viewId, BaseFragment baseFragment) {
        try {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(viewId, baseFragment, baseFragment.getClass().getSimpleName());
            fragmentTransaction.commit();
            mCurrentBaseFragment = baseFragment;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回
     */
    public void doBack(View view) {
        onBackPressed();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 记录触摸时间
            touchOverTime = System.currentTimeMillis();
            if (isFastDoubleClick()) {
                return true;
            }
            if (isRefreshing){
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 防止重复点击
     * @return
     */
    protected boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 0 < timeD && timeD < 400) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout() {
        setImmerseLayout(null, null);
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout(View parentView, View childView) {
        setImmerseLayout(parentView, childView, false);
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout(View parentView, View childView, boolean isDark) {
        fullScreen(this);
        setStatusPaddingAndTextColor(parentView, childView, isDark);
    }

    /**
     * 通过设置全屏，设置状态栏透明
     *
     * @param activity
     */
    private void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
            Window window = activity.getWindow();
            View decorView = window.getDecorView();
            //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }


    private void setStatusPaddingAndTextColor(View parentView, View childView, boolean isDark) {
        //判断版本是5.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setBarTitleTextColor(isDark);
            int statusHeight = ScreenUtils.getStatusHeight(this);
            if (null != parentView) {
                ViewGroup.LayoutParams parentParams = parentView.getLayoutParams();
                parentParams.height = statusHeight + getResources().getDimensionPixelOffset(R.dimen.home_top_height);
                parentView.setLayoutParams(parentParams);
            }
            if (null != childView) {
                //设置系统栏需要的内偏移
                ScreenUtils.setMargins(childView, 0, statusHeight, 0, 0);
            }
        } else {
            if (null != parentView) {
                ViewGroup.LayoutParams parentParams = parentView.getLayoutParams();
                parentParams.height = getResources().getDimensionPixelOffset(R.dimen.home_top_height);
                parentView.setLayoutParams(parentParams);
            }
        }
    }

    /**
     * 设置状态栏字体颜色
     *
     * @param isDark
     */
    protected void setBarTitleTextColor(boolean isDark) {
        if (Build.VERSION.SDK_INT >= 21) {
            //setTranslucentStatus(true);
            // 小米手机沉浸式状态栏黑色透明
            SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
            // 设置状态栏的文字颜色
            systemBarTintManager.setStatusBarDarkMode(isDark, this);
            View decorView = getWindow().getDecorView();

            int option;
            if (isDark) {
                option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                //新版miui设黑色文字方法
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            } else {
                option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            }

            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 设置状态栏是否透明
     *
     * @param on
     */
    @TargetApi(19)
    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static void setWindowStatusBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *
     */
    @Override
    public void finish() {
        // 判断是否返回MainActivity
        if (!isExitLogin && !(this instanceof MainActivity)) {
            if (!Utils.isExistMainActivity(MainActivity.class, this)) {
                openActivity(MainActivity.class);
            }
        }
        super.finish();
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 申请权限
     */
    public void checkPermissions(boolean isSqCode) {
        try {
            List<String> permissionList = new ArrayList<>();
            for (String permission : permissions) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                    permissionList.add(permission);
                }
            }
            if (permissionList.size() > 0) {
                if (isSqCode){
                    ActivityCompat.requestPermissions(this, permissionList.toArray(new String[]{}), REQUEST_REQUEST_SQ_CODE);
                }else {
                    ActivityCompat.requestPermissions(this, permissionList.toArray(new String[]{}), REQUEST_REQUEST_CODE);
                }
                return;
            }
            permissionNextTips(isSqCode);

        } catch (Throwable e) {
            Log.e("checkPermissions", "", e);
        }
    }

    public void permissionNextTips(boolean isSqCode) {
        if (isSqCode) {
            skipToSqCode(null);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_REQUEST_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //Toast.makeText(this, "权限被拒绝： "+permissions[i], Toast.LENGTH_SHORT).show();

                        // 二次请求，表现为：以前请求过这个权限，但是用户拒接了
                        // 在二次请求的时候，会有一个“不再提示的”checkbox
                        // 因此这里需要给用户解释一下我们为什么需要这个权限，否则用户可能会永久不在激活这个申请
                        // 方便用户理解我们为什么需要这个权限
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                            setPermissionDialog();
                        }
                        // 到这里就表示已经是第3+次请求，而且此时用户已经永久拒绝了，这个时候，我们引导用户到应用权限页面，让用户自己手动打开
                        else {
                            Toast.makeText(this, "部分权限被拒绝获取，将会会影响后续功能的使用，建议重新打开", Toast.LENGTH_LONG).show();
                            openAppPermissionSetting(REQUEST_SETTING_WHAT);
                        }
                        return;
                    }
                }

                // 到这里就表示用户允许了本次请求，我们继续检查是否还有待申请的权限没有申请
                if (isAllRequestedPermissionGranted()) {
                    permissionNextTips(false);
                } else {
                    checkPermissions(false);
                }
                break;
            case REQUEST_REQUEST_SQ_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //Toast.makeText(this, "权限被拒绝： "+permissions[i], Toast.LENGTH_SHORT).show();

                        // 二次请求，表现为：以前请求过这个权限，但是用户拒接了
                        // 在二次请求的时候，会有一个“不再提示的”checkbox
                        // 因此这里需要给用户解释一下我们为什么需要这个权限，否则用户可能会永久不在激活这个申请
                        // 方便用户理解我们为什么需要这个权限
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                            setPermissionDialog();
                        }
                        // 到这里就表示已经是第3+次请求，而且此时用户已经永久拒绝了，这个时候，我们引导用户到应用权限页面，让用户自己手动打开
                        else {
                            Toast.makeText(this, "部分权限被拒绝获取，将会会影响后续功能的使用，建议重新打开", Toast.LENGTH_LONG).show();
                            openAppPermissionSetting(REQUEST_SETTING_WHAT);
                        }
                        return;
                    }
                }

                // 到这里就表示用户允许了本次请求，我们继续检查是否还有待申请的权限没有申请
                if (isAllRequestedPermissionGranted()) {
                    permissionNextTips(false);
                } else {
                    checkPermissions(false);
                }
                break;
        }
    }

    public void setPermissionDialog() {
        View.OnClickListener cancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissionDialog.dismiss();
                ToastUtils.showToast(BaseActivity.this, "权限尚未开启");
                //   ShowFragActivity.this.finish();
            }
        };

        View.OnClickListener sureClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissionDialog.dismiss();
                checkPermissions(false);
            }
        };

        permissionDialog = DialogUtils.createPermissionTip(this, "您需要同意授权才能拍照", "权限申请", "取消", "去设置",
                cancelClickListener, sureClickListener);
        permissionDialog.show();
    }

    public boolean isAllRequestedPermissionGranted() {
        for (final String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                return false;
            }
        }
        return true;
    }

    public boolean openAppPermissionSetting(int requestCode) {
        try {
            Intent intent =
                    new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + this.getPackageName()));
            intent.addCategory(Intent.CATEGORY_DEFAULT);

            // Android L 之后Activity的启动模式发生了一些变化
            // 如果用了下面的 Intent.FLAG_ACTIVITY_NEW_TASK ，并且是 startActivityForResult
            // 那么会在打开新的activity的时候就会立即回调 onActivityResult
            // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivityForResult(intent, requestCode);
            return true;
        } catch (Throwable e) {
        }
        return false;
    }
}
